<template>
  <div class="smart-plan-edit-container" v-loading="loading">
    <div class="fe-page-header">
      <div class="fe-page-header__left">
        {{ pageTitle }}
      </div>
      <div class="fe-page-header__right">
        <el-button
          class="fe-page-header__button"
          type="plain-third"
          :disabled="loading"
          @click="goBack"
        >
          {{$t('common.base.cancel')}}
        </el-button>
        <el-button
          v-if="currentStep > 0"
          class="fe-page-header__button"
          type="plain-third"
          :disabled="loading"
          @click="prev"
        >
          {{$t('common.base.steps.previous')}}
        </el-button>
        <el-button
          v-if="currentStep < 2"
          class="fe-page-header__button"
          type="primary"
          :disabled="loading"
          @click="next"
        >
          {{$t('common.base.steps.next')}}
        </el-button>
        <el-button
          v-if="currentStep == 2"
          class="fe-page-header__button"
          type="primary"
          :disabled="loading"
          @click="submit"
        >
          {{$t('common.base.finish')}}
        </el-button>
      </div>
    </div>
    <div class="plan-form-container" v-if="isInit">
      <div class="plan-process-steps">
        <el-steps :active="currentStep" align-center>
          <el-step :title="$t('smartPlan.steps[0]')"></el-step>
          <el-step :title="$t('smartPlan.steps[1]')"></el-step>
          <el-step :title="$t('smartPlan.steps[2]')"></el-step>
        </el-steps>
      </div>
      <div class="plan-form-wrap">
        <first-step
          ref="firstStep"
          v-show="currentStep == 0"
          :biz-type="bizType"
          :fields="fields"
          :task-config="taskConfig"
          :event-config="eventConfig"
          :action="action"
          :edit-value="formValue.planForm"
          :edit-allot-setting="formValue.allotSetting"
        ></first-step>
        <second-step
          ref="secondStep"
          v-show="currentStep == 1"
          :biz-type="bizType"
          :fields="fields"
          :edit-conditions="formValue.conditions"
          :edit-linkman-setting="formValue.linkmanSetting"
          :customers="createSmartPlanData.customers"
          :products="createSmartPlanData.products"
        ></second-step>
        <third-step
          ref="thirdStep"
          v-show="currentStep == 2"
          :action="action"
          :biz-type="bizType"
          :fields="fields"
          :plan-basic-data="firstParams.planBasicData"
          :plan-range="secondParams.conditions"
          :edit-form="formValue.thirdForm"
        ></third-step>
      </div>
    </div>
  </div>
</template>

<script>
/* components */
import firstStep from './components/firstStep.vue'
import secondStep from './components/secondStep.vue'
import thirdStep from './components/thirdStep.vue'
/* api */
import { getTriggerFieldList, createOrUpdate, checkPlanRange, getDetail } from '@src/modules/smartPlan/api/index.js'
import { getTenantConfigData } from '@src/api/SettingApi'
/* mixin */
import SmartPlanMixin from '@src/modules/smartPlan/mixin/index.js'
/* utils */
import { packToForm } from '../util/index'
import { getUserGuideStorageBase, setUserGuideStorageBase } from 'src/util/guideStorage.ts';
import qs from 'qs'

const SMART_PLAN_GUIDE = 'smart-plan-detail-guide'

export default {
  name: 'smart-plan-edit',
  mixins: [SmartPlanMixin],
  data() {
    return {
      loading: false,
      planId: '',
      formValue: {},
      isInit: false,
      currentStep: 0,
      createSmartPlanData: {},
      bizType: 'TASK', // 业务类型 TASK:工单 EVENT：事件 PAAS：paas
      planTypeId: '',
      disabled: false,
      fields: [],
      taskConfig: {}, // 工单配置
      eventConfig: {}, // 事件配置
      firstParams: {}, // 第一步数据
      secondParams: [], // 第二步数据
      thirdParams: {}, // 第三步数据
    }
  },
  computed: {
    action() {
      if (location.pathname.indexOf('/smart/plan/edit') > -1) {
        return 'edit'
      }
      if (location.pathname.indexOf('/smart/plan/copy') > -1) {
        return 'copy'
      }
      return 'create'
    },
    pageTitle() {
      if (this.action == 'create' || this.action == 'copy') {
        return `${this.createSmartPlanData.planName || ''} (${this.createSmartPlanData.planTypeName || ''})`
      }
      return `${this.formValue.planName || ''} (${this.formValue.planTypeName || ''})`
    },
  },
  async created() {
    try {
      let query = qs.parse(window.location.search.substr(1)) || {};
      this.planId = query.planId
      const data = JSON.parse(localStorage.getItem('createSmartPlanData') || '{}')
      this.createSmartPlanData = data
      this.bizType = data.planType || 'TASK'

      this.planTypeId = data.planTypeId
    } catch (e) {
      console.error('get createSmartPlanData error:', e)
    }
    this.initialize()
    this.getTenantConfig()
  },
  methods: {
    async initialize() {
      let subtask = [getTriggerFieldList({ bizType: this.bizType, formId: this.planTypeId, })];
      if (['edit', 'copy'].includes(this.action) && this.planId) {
        subtask.push(getDetail({ id: this.planId }))
      }
      this.loading = true
      const result = await Promise.all(subtask);
      const fields = result[0]?.data || []
      this.fields = fields.map(f => {
        if (['customer', 'product', 'linkman', 'customerAddress'].includes(f.formType)) {
          f.disabled = true
        }
        return f
      })

      if (['edit', 'copy'].includes(this.action)) {
        this.formValue = packToForm(result[1]?.data || {}, this.fields)
        this.secondParams = {
          linkmanSetting: this.formValue?.linkmanSetting || 0,
          conditions: this.formValue?.planRange || []
        }
        this.firstParams.planBasicData = this.formValue?.planBasicData || []
      }
      this.isInit = true
      this.loading = false
      this.initSmartPlanGuide()
    },
    goBack() {
      let id = window.frameElement.dataset.id
      return this.$platform.closeTab(id)
    },
    getTenantConfig() {
      getTenantConfigData().then(res => {
        this.taskConfig = res.data?.taskConfig || {}
        this.eventConfig = res.data?.serviceStationConfig || {}
      })
    },
    prev() {
      this.currentStep -= 1
    },
    async next() {
      if (this.currentStep == 0) {
        const valid = await this.$refs.firstStep.validate()
        if (valid) {
          this.loading = true
          this.firstParams = this.$refs.firstStep.buildParams()
          this.currentStep += 1
          this.loading = false
        }
      } else if (this.currentStep == 1) {
        let valid = await this.$refs.secondStep.validate()
        if (valid) {
          this.loading = true
          const params = this.$refs.secondStep.buildParams()
          const res = await checkPlanRange(params.conditions)
          this.loading = false
          // res.data为true代表没有匹配到数据
          if (res.data) {
            return this.$platform.notification({
              title: this.$t('smartPlan.planRangeNoDataTip'),
              type: 'error'
            })
          }
          if (!res.succ) {
            return this.$platform.notification({
              title: res.message,
              type: 'error'
            })
          }
          this.secondParams = params
          this.currentStep += 1
        } else {
          this.$platform.notification({
            title: this.$t('smartPlan.selectPlanRange'),
            type: 'error'
          })
        }
      }
    },
    async submit() {
      const valid = await this.$refs.thirdStep.validate()
      if (valid) {
        const firstParams = this.$refs.firstStep.buildParams()
        const secondParams = this.$refs.secondStep.buildParams()
        const thirdParams = this.$refs.thirdStep.buildParams()
        const params = {
          planName: this.createSmartPlanData.planName,
          planType: this.createSmartPlanData.planType,
          planTypeId: this.createSmartPlanData.planTypeId,
          planBasicData: JSON.stringify(firstParams.planBasicData), // 表单数据
          allotSetting: JSON.stringify(firstParams.allotSetting), // 工单事件派单设置
          planRange: JSON.stringify(secondParams.conditions), // 计划范围
          linkmanSetting: secondParams.linkmanSetting, // 联系人设置
          createDimension: thirdParams.createDimension,
          startSetting: JSON.stringify(thirdParams.startSetting),
          endSetting: JSON.stringify(thirdParams.endSetting),
          periodSetting: JSON.stringify(thirdParams.periodSetting),
        }
        if (this.action == 'edit') {
          params.id = this.planId
        }
        this.loading = true
        createOrUpdate(params).then(res => {
          this.loading = false
          let isSucc = res.success || res.succ;
          
          this.$platform.notification({
            type: isSucc ? 'success' : 'error',
            title: isSucc ? this.$t('common.base.tip.operationSuccess') : this.$t('common.base.tip.operationFail'),
            message: !isSucc && res.message
          })
          // 操作成功后关闭当前页面并刷新from页面
          if (isSucc) {
            this.closeAndRefreshFromTab()
          }
        })
      }
    },
    // 智能计划引导
    async initSmartPlanGuide() {
      // 判断是否完成
      let id = SMART_PLAN_GUIDE
      let userGuideStorage = await getUserGuideStorageBase()
      let isComplete = userGuideStorage?.[id]?.isComplete
      if (isComplete) return
      this.$nextTick(() => {
        this.smartPlanGuide()
      })
    },
    smartPlanGuide() {
      let id = SMART_PLAN_GUIDE
      let lastFinish = 1;
      let arr = [
        {
          content: this.$t('common.guide.smartPlan.content7'),
          haveStep: false,
          nowStep: 1,
          id,
          domObj: () => {
            return document.querySelectorAll('.el-step')[1];
          },
          lastFinish,
          stepTotalSetting:{
            finishBtn: this.$t('common.base.iKnow'),
          }
        }
      ]
      this.$Guide(arr, 0, '', e => {
        return new Promise((resolve, reject) => {
          resolve();
        });
      })
        .create()
        .then(vueDom => {
          if (vueDom) {
            setUserGuideStorageBase({
              userGuideList: [
                {
                  type: id,
                  step: 1,
                  isComplete: 1
                }
              ]
            });
          }
        });
    },
  },
  components: {
    firstStep,
    secondStep,
    thirdStep,
  }
}
</script>

<style lang="scss" scoped>
.smart-plan-edit-container {
  padding: 12px;
  border-radius: 4px;
  height: 100%;
  overflow: auto;
  width: 100%;
  .plan-form-container {
    background-color: #fff;
    height: calc(100% - 56px);
    overflow: auto;
    padding: 16px;
    .plan-form-wrap {
      padding-top: 16px;
      max-width: 824px;
      margin: 0 auto;
    }
  }
  .plan-process-steps {
    margin: 8px auto 0;
    max-width: 665px;
    width: 100%;
  }
  ::v-deep .el-step__title.is-process {
    color: $color-primary;
  }
  ::v-deep .el-step__head.is-process {
    color: $color-primary;
    border-color: $color-primary;
  }
}
</style>